//
//  ProductContentViewController.m
//  OutesIOS
//
//  Created by norman on 2019/1/5.
//  Copyright © 2019 norman. All rights reserved.
//

#import "ProductContentViewController.h"
#import "ProductListCommonResponse.h"
#import <TPKeyboardAvoidingTableView.h>
#import "ProjectData.h"
#import "GuidData.h"
#import "SearchData.h"
#import "ProductDetailViewController.h"
#import "ProductTableViewCell.h"
#import "CacheData.h"
#import "MJRefresh.h"
#import "ProductXlViewController.h"
#import "FjpgViewController.h"
#import "ProductListViewController.h"

@interface ProductContentViewController (){
    NSUInteger beginIndex;
    NSUInteger endIndex;
    BOOL showSearchTable;
}

@property (nonatomic,strong) UISearchBar *productSearchBar;
@property (nonatomic,strong) TPKeyboardAvoidingTableView *tableView;
@property (nonatomic,retain) NSMutableArray *dataSource;
@property (nonatomic,retain) NSMutableArray *OriginDataSource;
@property (nonatomic,copy) NSString *searchStr;

@end

@implementation ProductContentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    UITapGestureRecognizer *tapGr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)];
    tapGr.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tapGr];
    
    self.title = @"产品";
    
    [self initData];
    [self setupViews];
    [self loadData];
}

-(void)viewTapped:(UITapGestureRecognizer*)tapGr
{
    if ([self.productSearchBar isFirstResponder]) {
        [self.productSearchBar resignFirstResponder];
    }
}

/**
 *  初始化数据
 */
- (void)initData {
    beginIndex = 0;
    endIndex = LIST_PAGE_ITEM_COUNTS - 1;
    self.dataSource = [NSMutableArray new];
    self.OriginDataSource = [NSMutableArray new];
    showSearchTable = NO;
}

#pragma mark - 初始化视图
- (void)setupViews{
//    
//    //使用UISearchBar
//    self.productSearchBar = [[UISearchBar alloc]init];
//    //设置bar的frame
//    self.productSearchBar.frame = CGRectMake(0, 0, 300, 35);
//    self.productSearchBar.placeholder = @"请输入产品系列、型式、型号搜索关键字";
//    //修改placeholder字体的颜色和大小
//    UITextField * searchField = [self.productSearchBar valueForKey:@"_searchField"];
//    [searchField setValue:CM_PLACEHOLDER_TEXT_COLOR forKeyPath:@"_placeholderLabel.textColor"];
//    [searchField setValue:[UIFont systemFontOfSize:14] forKeyPath:@"_placeholderLabel.font"];
//    if (@available(iOS 11.0, *)) {
//        [[self.productSearchBar.heightAnchor constraintEqualToConstant:44.0] setActive:YES];
//    }
//    self.productSearchBar.showsCancelButton = NO;
//    self.productSearchBar.delegate = self;
//    self.navigationItem.titleView = self.productSearchBar;
    
    self.tableView = [[TPKeyboardAvoidingTableView alloc] initWithFrame:[UIView frameWithOutNav] style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    //去掉多余的分割线
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    
    //下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        if (self->showSearchTable) {
            [self refreshData];
        }
        else {
            [self.tableView.mj_header endRefreshing];
        }
        
    }];
    //上拉加载
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        if (self->showSearchTable) {
            [self loadMoreData];
        }
        else {
            [self.tableView.mj_footer endRefreshing];
        }
    }];
    
    [self.view addSubview:self.tableView];
}

#pragma mark - 加载数据
/**
 *  加载视图所有的数据
 */
- (void)loadData {
    //先从缓存里读取
    //    self.OriginDataSource = [[CacheData sharedDataBase] getArrayResponseWithUserName:[[AccountManager manager] token] andUrl:HTTP_GET_ALL_PRODUCTS andParam:@"" andModel:NSStringFromClass([SearchData class])];
    //    if (self.OriginDataSource != nil && self.OriginDataSource.count > 0) {
    //        [self.dataSource addObjectsFromArray:self.OriginDataSource];
    //        //刷新数据
    //        [self.tableView reloadData];
    //    }
    //    else {
    //
    //    }
    [self loadProductVersion];
}

- (void)refreshData {
    // 马上进入刷新状态
    [self.tableView.mj_header beginRefreshing];
    
    beginIndex = 0;
    endIndex = LIST_PAGE_ITEM_COUNTS - 1;
    [self searchProducts:self.searchStr];
}

- (void)loadMoreData {
    //下级公司发布的意见
    if (self.dataSource.count == 0) {
        return;
    }
    // 马上进入刷新状态
    [self.tableView.mj_footer beginRefreshing];
    beginIndex = self.dataSource.count;
    endIndex = beginIndex + LIST_PAGE_ITEM_COUNTS - 1;
    [self searchProducts:self.searchStr];
}


- (void)loadProductVersion {
    [HttpClient getWithUrl:HTTP_GET_ALL_PRODUCTS token:[[AccountManager manager]token] paramDic:nil resultClass:[SearchData class] success:^(SearchData *obj) {
        if (obj != nil) {
            
            //判断有木有版本升级
            NSString *lastDBVersion = [[NSUserDefaults standardUserDefaults] objectForKey:ProductDBVersionKey];
            if ([lastDBVersion intValue] != obj.getProductDbVersionResult) {
                //存储这次版本号
                [Tools saveKeyValues:[NSString stringWithFormat:@"%d", obj.getProductDbVersionResult] forKey:ProductDBVersionKey];
                //版本
                //重新加载数据
                //                [self loadAllProducts];
            }
            else {
                //已经从缓存里读取了数据
                //                self.OriginDataSource = [[CacheData sharedDataBase] getArrayResponseWithUserName:[[AccountManager manager] token] andUrl:HTTP_GET_ALL_PRODUCTS andParam:@"" andModel:NSStringFromClass([SearchData class])];
                //                if (self.OriginDataSource != nil && self.OriginDataSource.count > 0) {
                //
                //                }
                //                else {
                //                    //没有从缓存里读出来，那就再加载数据把
                //                    [self loadAllProducts];
                //                }
            }
            
        }
    } failure:^(NSError *error) {
        CMLog(@"获取产品失败：%@", error);
    }];
}

//- (void)loadAllProducts {
//    NSMutableDictionary *param = [NSMutableDictionary dictionary];
//    [param setValue:[NSNumber numberWithInt:0] forKey:@"icd"];
//
//    [HttpClient getWithUrl:HTTP_GET_ALL_PRODUCTS token:[[AccountManager manager]token] paramDic:param resultClass:[SearchData class] success:^(SearchData *obj) {
//        if (obj.getAllProductsResult != nil && obj.getAllProductsResult.count > 0) {
//            [[CacheData sharedDataBase] setResponseWithUserName:[[AccountManager manager] token] andUrl:HTTP_GET_ALL_PRODUCTS andParam:@"" andDateTime:@"2015-12-31 00:00:00" andResponse:obj.getAllProductsResult];
//            [self.OriginDataSource addObjectsFromArray:obj.getAllProductsResult];
//            [self.dataSource addObjectsFromArray:obj.getAllProductsResult];
//            [self.tableView reloadData];
//        }
//    } failure:^(NSError *error) {
//        CMLog(@"获取产品失败：%@", error);
//    }];
//}

- (void)searchProducts:(NSString*)keyword {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:[NSNumber numberWithInt:0] forKey:@"icd"];
    [param setValue:[NSNumber numberWithInteger:beginIndex] forKey:@"si"];
    [param setValue:[NSNumber numberWithInteger:endIndex] forKey:@"ei"];
    [param setValue:keyword forKey:@"kw"];
    showSearchTable = NO;
    
    [HttpClient getWithUrl:HTTP_GET_SEARCH_PRODUCTS token:[[AccountManager manager]token] paramDic:param resultClass:[SearchData class] success:^(SearchData *obj) {
        self->showSearchTable = YES;
        if (self->beginIndex == 0) {
            [self.tableView.mj_header endRefreshing];
            [self.dataSource removeAllObjects];
        }
        else {
            [self.tableView.mj_footer endRefreshing];
        }
        if (obj.searchResult != nil && obj.searchResult.count > 0) {
            [self.dataSource addObjectsFromArray:obj.searchResult];
        }
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        if (self->beginIndex == 0) {
            [self.tableView.mj_header endRefreshing];
        }
        else {
            [self.tableView.mj_footer endRefreshing];
        }
        CMLog(@"获取产品失败：%@", error);
    }];
}

- (void)loadProductSeries:(NSString *)tag {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:tag forKey:@"tag"];
    [param setValue:[NSNumber numberWithInt:1] forKey:@"ac"]; //0 仅包括未上市  1 仅包括已上市 2 已上市未上市都包括
    
    [HttpClient getWithUrl:HTTP_GET_PRODUCT_SERIES token:[[AccountManager manager]token] paramDic:param resultClass:[GuidData class] success:^(GuidData *obj) {
        CMLog(@"%@", obj);
    } failure:^(NSError *error) {
        CMLog(@"%@", error);
    }];
    
}


#pragma mark - 事件的响应
/**
 *  called when text changes (including clear)
 *
 *  @param searchBar  <#searchBar description#>
 *  @param searchText <#searchText description#>
 */
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    if (searchBar.text.length == 0) {
        //加载所有的产品
        showSearchTable = NO;
        [self.dataSource removeAllObjects];
        [self.dataSource addObjectsFromArray:self.OriginDataSource];
        [self.tableView reloadData];
    }
}
/**
 *  用户编辑时的响应
 *
 *  @param searchBar 控件的ID
 */
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
    NSLog(@"%@", searchBar.text);
}

/**
 *  called when keyboard search button
 *
 *  @param searchBar <#searchBar description#>
 */
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    NSLog(@"%@", searchBar.text);
    NSLog(@"%@", searchBar.text);
    if ([self.productSearchBar isFirstResponder]) {
        [self.productSearchBar resignFirstResponder];
    }
    self.searchStr = [[NSString alloc] initWithString:searchBar.text];
    [self searchProducts:searchBar.text];
}




#pragma mark - tableView显示设置数据
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (!showSearchTable) {
        return 5;
    }
    return self.dataSource.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (!showSearchTable) {
        static NSString *identifier = @"type_Cell_Identifier";
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        cell.textLabel.textColor = CM_TABLE_TITLE_COLOR;
        cell.textLabel.font = [UIFont systemFontOfSize:kListTitleFontSize];
        if (indexPath.row == 0) {
            cell.imageView.image = [UIImage imageNamed:@"product_snj"];
            cell.textLabel.text = @"风机盘管";
        }else if (indexPath.row == 1){
            cell.imageView.image = [UIImage imageNamed:@"product_syj"];
            cell.textLabel.text = @"室外机";
        }
        else if (indexPath.row == 2){
            cell.imageView.image = [UIImage imageNamed:@"product_dr"];
            cell.textLabel.text = @"净水器";
        }
        else if (indexPath.row == 3){
            cell.imageView.image = [UIImage imageNamed:@"product_rsq"];
            cell.textLabel.text = @"空气能热水器";
        }
        else if (indexPath.row == 4){
            cell.imageView.image = [UIImage imageNamed:@"product_xfxt"];
            cell.textLabel.text = @"新风系统";
        }
        return cell;
    }
    static NSString *identifier = @"ProductCell";
    ProductTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[ProductTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    SearchData *item = [self.dataSource objectAtIndex:indexPath.row];
    [cell setProductTitle:item.xh andXl:item.xl andXs:item.xs];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (!showSearchTable) {
        return 44;
    }
    static NSString *identifier = @"ProductCell";
    ProductTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[ProductTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
    }
    SearchData *item = [self.dataSource objectAtIndex:indexPath.row];
    BOOL hasXl = NO;
    if (![item.xl isKindOfClass:[NSNull class]] && ![item.xl isEmpty]) {
        hasXl = YES;
    }
    BOOL hasXs = NO;
    if (![item.xs isKindOfClass:[NSNull class]] && ![item.xs isEmpty]) {
        hasXs = YES;
    }
    return [cell getHeight:hasXl andXs:hasXs];
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (!showSearchTable) {
        //跳转到列表页面
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        ProductListViewController *view = [ProductListViewController new];
        view.title = cell.textLabel.text;
        switch (indexPath.row) {
            case 0:
                //室内机
            {
                FjpgViewController *vc = [FjpgViewController new];
                [self.navigationController pushViewController:vc animated:YES];
                return;
            }
                break;
            case 1:
                //主机机
                view.product_type = MACHINE_TAG_FOR_MAIN;
                break;
            case 2:
                //轻型商用空调
                view.product_type = MACHINE_TAG_FOR_WATER_CLEANER;
                break;
            case 3:
                //空气能热水机
                view.product_type = MACHINE_TAG_FOR_KQNRSJ;
                break;
            case 4:
                //新风系统
                view.product_type = MACHINE_TAG_FOR_QRJHQ;
                break;
            default:
                break;
        }
        [self.navigationController pushViewController:view animated:YES];
        return;
    } else {
        SearchData *item = [self.dataSource objectAtIndex:indexPath.row];
        ProductDetailViewController *view = [ProductDetailViewController new];
        view.product_type = item.tag;
        view.equip_id = item.guidId;
        [self.navigationController pushViewController:view animated:YES];
    }
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, CGFLOAT_MIN)];
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, CGFLOAT_MIN)];
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}


#pragma mark - 触碰屏幕隐藏键盘
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    if ([self.productSearchBar isFirstResponder]) {
        [self.productSearchBar resignFirstResponder];
    }
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
